import json as js

import requests

from common.logger import logFile
# from common.read_config import load_ini
log = logFile()

class ApiRequest:

    def __init__(self):
        # self.api_root_url = load_ini('host')['root_url']
        self.session = requests.Session()



    def request_log(self, url, method, data=None, json=None, params=None, headers=None, files=None, cookies=None,
                    **kwargs):
        log.info("接口请求地址 ==>> {}".format(url))
        log.info("接口请求方式 ==>> {}".format(method))
        # Python3中，json在做dumps操作时，会将中文转换成unicode编码，因此设置 ensure_ascii=False
        log.info("接口请求头 ==>> {}".format(js.dumps(headers, indent=4, ensure_ascii=False)))
        # log.info("接口请求体 data 参数 ==>> {}".format(js.dumps(data, indent=4, ensure_ascii=False)))
        # log.info("接口请求 params 参数 ==>> {}".format(js.dumps(params, indent=4, ensure_ascii=False)))
        log.info("接口请求体 json 参数 ==>> {}".format(js.dumps(json, indent=4, ensure_ascii=False)))
        log.info("接口上传附件 files 参数 ==>> {}".format(files))
        log.info("接口 cookies 参数 ==>> {}".format(js.dumps(cookies, indent=4, ensure_ascii=False)))


class BaseRequest:
    def __init__(self, method, url, params_type, header=None, file=None, **kwargs):
        self.method = method
        self.url = load_ini('host')['root_url'] + url
        self.params_type = params_type
        self.header = header
        self.file = file
        self.s = requests.Session()
        self.kwargs = kwargs

    def send_request(self, ids=None, header=None, data=None):
        if ids is not None:
            url = self.url + ids

        else:
            url = self.url

        if header is not None:
            headers = self.header.update(header)

        else:
            headers = self.header

        if data is not None:
            datas = data

        else:
            datas = None

        if self.params_type == 'params':
            res = self.s.request(
                method=self.method,
                url=url,
                params=datas,
                headers=headers)
        elif self.params_type == 'data':
            res = self.s.request(
                method=self.method,
                url=url,
                data=datas,
                files=self.file,
                headers=headers)
        elif self.params_type == 'json':

            res = self.s.request(
                method=self.method,
                url=url,
                json=datas,
                files=self.file,
                headers=headers)
        else:
            raise ValueError(
                '可选关键字为params, json, data')

        return res
